//
//  JCPublishActivityTVC.m
//  SquashSpark
//
//  Created by 郭吉成 on 2017/11/21.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "JCPublishActivityTVC.h"
#import "SQActionSheetView.h"
#import "SystemSelectPhotoManager.h"
#import "WSProgressHUD.h"
#import <Qiniu/QiniuSDK.h>
#import "UIImage+HXExtension.h"
#import "YFBaseRequest.h"
#import "YFMomentApi.h"
#import "JCClubApi.h"
#import "PhotoActionSheetViewController.h"

#define kFoldCellHeight         75
#define kPicCellHeight          240
#define kTitleCellHeight        152
#define kInformationCellHeight  265
#define kPlaceCellHeight        119
#define kContentCellHeight      119

typedef NS_ENUM(NSInteger, DateInputMode) {
    DateInputModeStandBy,
    DateInputModeStartDate,
    DateInputModeStartTime,
    DateInputModeEndDate,
    DateInputModeEndTime
};

@interface JCPublishActivityTVC ()

@property (assign, nonatomic) NSInteger pictureCellHeight;
@property (assign, nonatomic) NSInteger titleCellHeight;
@property (assign, nonatomic) NSInteger timeCellHeight;
@property (assign, nonatomic) NSInteger placeCellHeight;
@property (assign, nonatomic) NSInteger contentCellHeight;

@property (weak, nonatomic) IBOutlet UILabel *headerTitleLabel;

@property (weak, nonatomic) IBOutlet UITableViewCell *pictureCell;
@property (weak, nonatomic) IBOutlet UIImageView *coverImageView;
@property (weak, nonatomic) UIImage *coverImage;
@property (weak, nonatomic) NSURL *coverImageURL;
@property (weak, nonatomic) IBOutlet UIButton *picCellButton;
@property (weak, nonatomic) IBOutlet UIButton *picCellButton2;

@property (weak, nonatomic) IBOutlet UITableViewCell *titleCell;
@property (weak, nonatomic) IBOutlet UITextField *activeTitleInput;
@property (weak, nonatomic) IBOutlet UIButton *titleCellButton;
@property (weak, nonatomic) IBOutlet UIButton *titleCellButton2;

@property (weak, nonatomic) IBOutlet UITableViewCell *timeCell;
@property (weak, nonatomic) IBOutlet UIButton *startTimeDate;
@property (weak, nonatomic) IBOutlet UIButton *startTime;
@property (weak, nonatomic) IBOutlet UIButton *endTimeDate;
@property (weak, nonatomic) IBOutlet UIButton *endTime;
@property (weak, nonatomic) IBOutlet UIButton *timeCellButton;
@property (weak, nonatomic) IBOutlet UIButton *timeCellButton2;
@property (strong, nonatomic) NSString *startTimeDateString;
@property (strong, nonatomic) NSString *startTimeString;
@property (strong, nonatomic) NSString *endTimeDateString;
@property (strong, nonatomic) NSString *endTimeString;

@property (weak, nonatomic) IBOutlet UITableViewCell *placeCell;
@property (weak, nonatomic) IBOutlet UITextField *placeInput;
@property (weak, nonatomic) IBOutlet UIButton *placeCellButton;
@property (weak, nonatomic) IBOutlet UIButton *placeCellButton2;

@property (weak, nonatomic) IBOutlet UITableViewCell *contentCell;
@property (weak, nonatomic) IBOutlet UITextField *contentInput;
@property (weak, nonatomic) IBOutlet UIButton *contentCellButton;
@property (weak, nonatomic) IBOutlet UIButton *contentCellButton2;

@property (weak, nonatomic) IBOutlet UIButton *submitButton;

@property (strong, nonatomic) UIDatePicker *datePicker;
@property (strong, nonatomic) UIView *dateView;
@property (assign, nonatomic) DateInputMode dateInputMode;
@property (strong, nonatomic) SystemSelectPhotoManager *photoManger;
@property (strong, nonatomic) WSProgressHUD *hud;
@end

@implementation JCPublishActivityTVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCode];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self foldAction:_picCellButton];
    });
}

- (void)initCode{
    self.navigationItem.title = @"Publishing activities";
    _pictureCellHeight =
    _titleCellHeight =
    _timeCellHeight =
    _placeCellHeight =
    _contentCellHeight = 75;
    
    _activeTitleInput.attributedPlaceholder = [self creatAttributedString:@"Fill in title" font:kOpenSansFont(OpenSansRegular, 16) color:[UIColor colorWithHex:0x999999]];
    _placeInput.attributedPlaceholder = [self creatAttributedString:@"Fill in specific places" font:kOpenSansFont(OpenSansRegular, 16) color:[UIColor colorWithHex:0x999999]];
    _contentInput.attributedPlaceholder = [self creatAttributedString:@"Fill in specific content" font:kOpenSansFont(OpenSansRegular, 16) color:[UIColor colorWithHex:0x999999]];
    
    _submitButton.layer.cornerRadius = 3;
    _submitButton.layer.masksToBounds = YES;
    
}

- (NSAttributedString *)creatAttributedString:(NSString *)contentString
                                         font:(UIFont *)font
                                        color:(UIColor *)color{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    attrs[NSForegroundColorAttributeName] = color;
    NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:contentString attributes:attrs];
    return attStr;
}

- (IBAction)foldAction:(UIButton *)sender{
    sender.selected = !sender.selected;
    BOOL isFold = !sender.selected;
    
    if (sender.tag == _picCellButton.tag) {
        if (isFold) {
            _pictureCellHeight = kFoldCellHeight;
        }else{
            _pictureCellHeight = kPicCellHeight;
        }
        if (sender == _picCellButton) {
            _picCellButton2.selected = sender.selected;
        }else{
            _picCellButton.selected = sender.selected;
        }
    }else if (sender.tag == _titleCellButton.tag) {
        if (isFold) {
            _titleCellHeight = kFoldCellHeight;
        }else{
            _titleCellHeight = kTitleCellHeight;
        }
        if (sender == _titleCellButton) {
            _titleCellButton2.selected = sender.selected;
        }else{
            _titleCellButton.selected = sender.selected;
        }
    }else if (sender.tag == _timeCellButton.tag) {
        if (isFold) {
            _timeCellHeight = kFoldCellHeight;
        }else{
            _timeCellHeight = kInformationCellHeight;
        }
        if (sender == _timeCellButton) {
            _timeCellButton2.selected = sender.selected;
        }else{
            _timeCellButton.selected = sender.selected;
        }
    }else if (sender.tag == _placeCellButton.tag) {
        if (isFold) {
            _placeCellHeight = kFoldCellHeight;
        }else{
            _placeCellHeight = kPlaceCellHeight;
        }
        if (sender == _placeCellButton) {
            _placeCellButton2.selected = sender.selected;
        }else{
            _placeCellButton.selected = sender.selected;
        }
    }else if (sender.tag == _contentCellButton.tag) {
        if (isFold) {
            _contentCellHeight = kFoldCellHeight;
        }else{
            _contentCellHeight = kContentCellHeight;
        }
        if (sender == _contentCellButton) {
            _contentCellButton2.selected = sender.selected;
        }else{
            _contentCellButton.selected = sender.selected;
        }
    }
    [self.view endEditing:YES];
    [UIView performWithoutAnimation:^{
         [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:sender.tag]] withRowAnimation:UITableViewRowAnimationNone];
    }];
//    [self.tableView beginUpdates];
//    [self.tableView reloadData];
//    [self.tableView endUpdates];
}

- (IBAction)dateAction:(UIButton *)sender {
    if (sender == _startTimeDate) {
        _dateInputMode = DateInputModeStartDate;
    }else{
        _dateInputMode = DateInputModeEndDate;
    }
    [self popDatePickerView:UIDatePickerModeDate];
}

- (IBAction)timeAction:(UIButton *)sender {
    if (sender == _startTime && _startTimeDateString) {
        _dateInputMode = DateInputModeStartTime;
         [self popDatePickerView:UIDatePickerModeTime];
    }else if(sender == _endTime && _endTimeDateString){
        _dateInputMode = DateInputModeEndTime;
         [self popDatePickerView:UIDatePickerModeTime];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return _pictureCellHeight;
    }else if (indexPath.section == 1) {
        return _titleCellHeight;
    }else if (indexPath.section == 2) {
        return _timeCellHeight;
    }else if (indexPath.section == 3) {
        return _placeCellHeight;
    }else if (indexPath.section == 4){
        return _contentCellHeight;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 4) {
        return 0;
    }else{
        return 7;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *foot = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"creatClubFoot"];
    if (foot == nil) {
        foot = [UIView new];
        foot.backgroundColor = [UIColor clearColor];
    }
    return foot;
}

- (UIDatePicker *)datePicker{
    if (_datePicker == nil) {
        _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, self.dateView.bounds.size.width, self.dateView.bounds.size.height - 40)];
    }
    return _datePicker;
}

- (UIView *)dateView{
    if (_dateView == nil) {
        _dateView = [[UIView alloc] initWithFrame:CGRectMake(0, kYFScreenHeight, kYFScreenWidth, 0.618 * kYFScreenWidth + 40)];
        _dateView.backgroundColor = [UIColor whiteColor];
        
        [_dateView addSubview:self.datePicker];
        
        UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancel setTitle:@"CANCEL" forState:UIControlStateNormal];
        [cancel setTitleColor:kBgThemeColor forState:UIControlStateNormal];
        cancel.titleLabel.font = kOpenSansFont(OpenSansRegular, 16);
        [cancel sizeToFit];
        cancel.center = CGPointMake(20+0.5*cancel.frame.size.width, 20);
        [cancel addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton *done = [UIButton buttonWithType:UIButtonTypeCustom];
        [done setTitle:@"DONE" forState:UIControlStateNormal];
        [done setTitleColor:kBgThemeColor forState:UIControlStateNormal];
        done.titleLabel.font = kOpenSansFont(OpenSansRegular, 16);
        [done sizeToFit];
        done.center = CGPointMake(kYFScreenWidth - 20 - 0.5*done.frame.size.width, 20);
        [done addTarget:self action:@selector(doneAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [_dateView addSubview:cancel];
        [_dateView addSubview:done];
    }
    return _dateView;
}

- (void)cancelAction:(UIButton *)sender{
    [self dismissDatePickerViewComplete:^{
        
    }];
}

- (void)doneAction:(UIButton *)sender{
    NSDate *date = self.datePicker.date;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSString *dateString;
    
    [self dismissDatePickerViewComplete:^{
        if (_dateInputMode == DateInputModeStandBy) {
            return ;
        }
        [self popDatePickerView:UIDatePickerModeTime];
    }];
    if (_dateInputMode == DateInputModeStartDate) {
        dateFormatter.dateFormat = @"YYYY-MM-dd";
        dateString = [dateFormatter stringFromDate:date];
        [_startTimeDate setTitle:dateString forState:UIControlStateNormal];
        _dateInputMode = DateInputModeStartTime;
        _startTimeDateString = dateString;
    }else if (_dateInputMode == DateInputModeStartTime){
        dateFormatter.dateFormat = @"HH:mm";
        dateString = [dateFormatter stringFromDate:date];
        _dateInputMode = DateInputModeStandBy;
        [_startTime setTitle:dateString forState:UIControlStateNormal];
        _startTimeString = dateString;
    }else if (_dateInputMode == DateInputModeEndDate) {
        dateFormatter.dateFormat = @"YYYY-MM-dd";
        dateString = [dateFormatter stringFromDate:date];
        [_endTimeDate setTitle:dateString forState:UIControlStateNormal];
        _dateInputMode = DateInputModeEndTime;
        _endTimeDateString = dateString;
    }else if (_dateInputMode == DateInputModeEndTime){
        dateFormatter.dateFormat = @"HH:mm";
        dateString = [dateFormatter stringFromDate:date];
        _dateInputMode = DateInputModeStandBy;
        [_endTime setTitle:dateString forState:UIControlStateNormal];
        _endTimeString = dateString;
    }
}

- (void)popDatePickerView:(UIDatePickerMode)mode {
    self.tableView.userInteractionEnabled = NO;
    [[UIApplication sharedApplication].keyWindow addSubview:self.dateView];
    [UIView animateKeyframesWithDuration:.3 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeCubic animations:^{
        self.dateView.center = CGPointMake(0.5 * kYFScreenWidth, kYFScreenHeight - 0.5*self.dateView.bounds.size.height);
        self.datePicker.datePickerMode = mode;
    } completion:^(BOOL finished) {
    }];
}

- (void)dismissDatePickerViewComplete:(void(^)(void)) complete{
    self.tableView.userInteractionEnabled = YES;
    [UIView animateKeyframesWithDuration:.3 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeCubic animations:^{
        self.dateView.center = CGPointMake(0.5 * kYFScreenWidth, kYFScreenHeight + 0.5*self.dateView.bounds.size.height);
    } completion:^(BOOL finished) {
        [self.dateView removeFromSuperview];
        if (complete) {
            complete();
        }
    }];
}

- (IBAction)coverAction:(UITapGestureRecognizer *)sender {
    [PhotoActionSheetViewController showInParentViewController:[[UIApplication sharedApplication] keyWindow].rootViewController alertType:UIAlertControllerStyleAlert animationType:DetailViewControllerPresentAnimationTypeUp actionBlock:^(kTapActionButtonType btnType) {
        [self gotoSeletePhotoOrTakePhoto:btnType];
    }].isTapCoverViewDismiss = YES;
}

- (void)gotoSeletePhotoOrTakePhoto:(kTapActionButtonType)type {
     __weak typeof(self)weakSelf = self;
    SystemSelectPhotoManager *photoManger = [SystemSelectPhotoManager selectPhotoManagerWithEditCaseType:kSystemDeflaut];
    self.photoManger = photoManger;
    [photoManger takePhotoBySource:type canEdit:YES parentViewController:self selectCallBlock:^(UIImage *selectImage, NSError *error) {
        weakSelf.coverImage = selectImage;
        weakSelf.coverImageView.image = selectImage;
    }];
}

- (IBAction)submitAction:(UIButton *)sender {
    if ([self checkInfoValid]) {
        [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
        __weak typeof(self)weakSelf = self;
        [self uploadImagesQNComplated:^(NSArray *imageUrlArr, NSError *error) {
            if (error) {
                [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
            }else{
                NSString *startTimeString = _startTimeDateString?[NSString stringWithFormat:@"%@ %@",_startTimeDateString,_startTimeString]:@"";
                NSString *endTimeString = _endTimeDateString?[NSString stringWithFormat:@"%@ %@",_endTimeDateString,_endTimeString]:@"";
                NSString *clubID;
                if ([User getUseInfo].adminClubs.count > 0) {
                    clubID = [User getUseInfo].adminClubs.firstObject.clubID;
                }else if ([User getUseInfo].joinClubs.count > 0){
                    clubID = [User getUseInfo].joinClubs.firstObject.clubID;
                }else{
                    clubID = @"0";
                }
                [JCClubApi createClubEventWithClubID:clubID
                                               title:_activeTitleInput.text
                                             content:_contentInput.text
                                          bannerList:imageUrlArr
                                               place:_placeInput.text
                                           startTime:startTimeString
                                             endTime:endTimeString
                                            complete:^(NSError *error) {
                                                if (error) {
                                                    [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
                                                }else{
                                                    [weakSelf.hud showSuccessWithStatus:@"Success!" dimissAfterSecond:2];
                                                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                                        [self.navigationController popViewControllerAnimated:YES];
                                                    });
                                                }
                                            }];
            }
        }];
    }
}

- (void)uploadImagesQNComplated:(void(^)(NSArray *imageUrlArr,NSError *error))completedBlock {
    
    __weak typeof(self) weakSelf = self;
    
    [[YFNetworkingService sharedInstance] sendRequest:[YFMomentApi requestApiWithType:kGetQiNiuUploadImageToMomentApi andParam:nil] callback:^(BOOL success, id result, NSError *error) {
        if (success == NO) {
            if (completedBlock) {
                completedBlock(nil,[NSError errorWithDomain:@"获取七牛token失败" code:-1001 userInfo:nil]);
            }
            return;
        }else {
            NSString *token = [[result responseInfo] objectForKey:@"token"];
            QNUploadOption *option = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
            }];
            NSArray *images = @[self.coverImage];
            [weakSelf upladToQNImages:images atIndex:0 token:token keys:[NSMutableArray array] filenamesArr:[NSMutableArray arrayWithCapacity:images.count] option:option completed:^(BOOL success, NSMutableArray *fileNameArr) {
                if (success) {
                    
                    NSMutableArray *arrM = [NSMutableArray array];
                    [fileNameArr enumerateObjectsUsingBlock:^(NSString *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        [arrM addObject:[NSString stringWithFormat:@"%@%@",kImageBaseUrl,obj]];
                    }];
                    if (completedBlock) {
                        completedBlock(arrM.copy,nil);
                    }
                    
                }else {
                    if (completedBlock) {
                        completedBlock(nil,[NSError errorWithDomain:@"Fail!" code:-1002 userInfo:nil]);
                    }
                }
            }];
        }
    }];
}

- (void)upladToQNImages:(NSArray <UIImage *>*)images
                atIndex:(NSInteger)index
                  token:(NSString *)token
                   keys:(NSMutableArray *)keys
           filenamesArr:(NSMutableArray *)filenamesArr
                 option:(QNUploadOption *)option
              completed:(void(^)(BOOL success,NSMutableArray *fileNameArr))completedBlock {
    
    UIImage *image = images[index];
    __block NSInteger imageIndex = index;
    NSData *data = [image compressToDataHX];
    
    
    NSTimeInterval time= [[NSDate date] timeIntervalSince1970];
    
    //拼接图片上传后的路径： http://staticapp.coollang.com/bq/club/+ uuid + 下划线 + 时间戳 + 下划线 + 序号 + 中划线 + 图片宽*图片高 + .jpg
    NSString *filename = [NSString stringWithFormat:@"bq/club/%@_%.f_%ld-%d*%d.%@",[User getLastUser].userID,time,(long)imageIndex,(int)image.size.width,(int)image.size.height,@"jpg"];
    [filenamesArr addObject:filename];
    
    [[YFNetworkingService qNUploadManager] putData:data key:filename token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if (info.isOK) {
            [keys addObject:key];
            YFLog(@"idInex %ld,OK",(long)index);
            imageIndex++;
            YFLog(@"上传完成,%@",filename);
            for (NSString *imgKey in keys) {
                NSLog(@"%@",imgKey);
            }
            if (completedBlock) {
                completedBlock(YES,filenamesArr);
            }
            if (index == 1) {
                return ;
            }
            if (imageIndex == images.count) {
                return;
            }
            [self upladToQNImages:images atIndex:imageIndex token:token keys:keys filenamesArr:filenamesArr option:option completed:completedBlock];
        }else{
            if (completedBlock) {
                completedBlock(NO,nil);
            }
            YFLog(@"上传失败,%@",filename);
        }
    } option:option];
}

- (BOOL)checkInfoValid{
    if (_coverImage == nil) {//NSLocalizedString(@"",@"")
        [self showAlertTitle:nil message:NSLocalizedString(@"Miss the cover", @"缺少封面")];
        return NO;
    }else if (_activeTitleInput.text.length > 100){
        [self showAlertTitle:nil message:NSLocalizedString(@"Title within 100 words",@"标题限制在100字以内")];
        return NO;
    }else if (_startTimeDateString == nil){
        [self showAlertTitle:nil message:NSLocalizedString(@"Please set up starting time",@"请设置起始时间")];
        return NO;
    }else if (_placeInput.text.length > 100){
        [self showAlertTitle:nil message:NSLocalizedString(@"Address within 100 words",@"地址限制在100字以内")];
        return NO;
    }else if (_contentInput.text.length > 100){
        [self showAlertTitle:nil message:NSLocalizedString(@"Content within 100 words",@"内容限制在100字以内")];
        return NO;
    }
    return YES;
}

- (void)showAlertTitle:(NSString *)titel message:(NSString *)message{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:titel message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *done = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:done];
    [self presentViewController:alert animated:YES completion:nil];
}

- (WSProgressHUD *)hud{
    if (_hud == nil) {
        _hud = [WSProgressHUD showOnView:self.view andString:@""];
        [_hud showWithMaskType:WSProgressHUDMaskTypeGradient];
        [_hud dismiss];
    }
    return _hud;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
